#include "app_mqtt.h"

static MQTTClient mqttclient;
static MQTTClient_message mqttmessage = MQTTClient_message_initializer;

/**
 * @brief   0 成功  非0 失败
 */
static int (*messageCallback)(char *message_payload);

/**
 * @brief 失联回调
 */
void app_mqtt_onConnectionLost(void *context, char *cause)
{
    log_error("MQTTClient_onConnectionLost:%s\n", cause);
    app_mqtt_init();
}

/**
 * @brief 接收消息的回调
 */
int app_mqtt_onMessageArrived(void *context, char *topicName, int topicLen, MQTTClient_message *message)
{
    log_info("MQTTClient_messageArrived:%s\n", message->payload);

    int ret = messageCallback(message->payload);
    if (ret == 0)
    {
        return 1; // 拧过来  paho要求1成功 0失败
    }
    else
    {
        return 0;
    }
}
/**
 * @brief 发送完成回调
 */
void app_mqtt_onDeliveryComplete(void *context, MQTTClient_deliveryToken dt)
{
    log_info(" delivery Complete  !! \n");
}

/**
 * @brief MQTT的初始化
 * 1 客户端初始化
 * 2 注册回调  3个  ：  失联 、接收、发送
 * 3 连接broker
 * 4 订阅主题
 */
int app_mqtt_init(void)
{
    //   * 1 客户端初始化
    int ret = MQTTClient_create(&mqttclient, MQTT_BROKER_IP, MQTT_CLIENT_ID, MQTTCLIENT_PERSISTENCE_NONE, NULL);
    if (ret != MQTTCLIENT_SUCCESS)
    {
        perror("MQTTClient_create");
        return -1;
    }
    log_info("MQTTClient_create success \n");
    /// 2注册回调  3个  ：  失联 、接收、发送
    MQTTClient_setCallbacks(mqttclient, NULL, app_mqtt_onConnectionLost, app_mqtt_onMessageArrived, app_mqtt_onDeliveryComplete);

    //  * 3 连接broker
    MQTTClient_connectOptions options = MQTTClient_connectOptions_initializer;
    ret = MQTTClient_connect(mqttclient, &options);
    if (ret == MQTTCLIENT_SUCCESS)
    {
        log_info("MQTTClient_connect success \n");
    }
    else
    {
        perror("MQTTClient_connect fail \n");
        MQTTClient_destroy(&mqttclient);
        return -1;
    }

    //  * 4 订阅主题
    ret = MQTTClient_subscribe(mqttclient, MQTT_TOPIC_RECV, 1);
    if (ret == MQTTCLIENT_SUCCESS)
    {
        log_info("MQTTClient_subscribe success \n");
    }

    return 0;
}

/**
 * @brief 发送消息
 */
int app_mqtt_sendMessage(char *message_payload)
{
    mqttmessage.payload = message_payload;
    mqttmessage.payloadlen = strlen(message_payload);
    mqttmessage.qos = 1;
    int ret = MQTTClient_publishMessage(mqttclient, MQTT_TOPIC_SEND, &mqttmessage, NULL);
    if (ret == MQTTCLIENT_SUCCESS)
    {
        log_info("MQTTClient_publishMessage success \n");
        return 0;
    }
    else
    {
        perror("MQTTClient_publishMessage fail \n");
        return -1;
    }
}

/**
 * @brief  注册接收消息的回调函数
 */
void app_mqtt_registerMessageCallback(int (*callback)(char *message_payload))
{
    messageCallback = callback;
}

/**
 * @brief 销毁mqtt
 */
void app_mqtt_destroy(void)
{
    MQTTClient_unsubscribe(mqttclient, MQTT_TOPIC_RECV);
    MQTTClient_disconnect(mqttclient, 1000);
    MQTTClient_destroy(&mqttclient);
}